<template>
  <div
    id="userManage"
    class="el-main-padding"
    v-loading="loading"
  >
    <div class="my-breadcrumb-div">
      <i class="el-icon-location my-breadcrumb-icon my-breadcrumb-padding" />
      <el-breadcrumb
        class="my-breadcrumb-padding"
        separator="/"
      >
        <el-breadcrumb-item>
          <!--配置-->
          {{ $t('message.userManage.breadcrumb.crumb1') }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <!--用户管理-->
          {{ $t('message.userManage.breadcrumb.crumb2') }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-row class="margin-bottom-row config-row">
      <el-col>
        <el-card>
          <div class="card-title font-size-el line-height-none">
            <!--用户-->
            {{ $t('message.userManage.card.title') }}
            <!--添加用户-->
            <el-button
              @click="handleUserCreate"
              style="padding: 0"
              type="text"
            >
              <i
                class="el-icon-plus"
                style="font-weight: bold;line-height: 1em;"
              />
            </el-button>
          </div>
          <el-table
            height="750px"
            class="table-gutter-background"
            header-row-class-name="test-table-row-class"
            header-cell-class-name="my-table-header-cell"
            cell-class-name="my-table-cell"
            :data="user.table.data"
          >
            <el-table-column
              type="index"
              width="50px"
            />
            <!--用户名-->
            <el-table-column
              :label="$t('message.userManage.card.table.header.col1')"
              prop="username"
              min-width="155px"
            />
            <!--管理员权限-->
            <el-table-column
              :label="$t('message.userManage.card.table.header.col2')"
              prop="coords"
              min-width="160px"
            >
              <template slot-scope="scope">
                <!--'有' : '无'-->
                {{ $t('message.userManage.card.table.content.col2', {is_staff: scope.row.is_staff}) }}
              </template>
            </el-table-column>
            <!--操作-->
            <el-table-column
              min-width="220px"
              :label="$t('message.common.label.operate')"
            >
              <template slot-scope="scope">
                <!--修改-->
                <el-button
                  class="no-padding"
                  @click.stop="handleUserModify(scope.row, scope.$index)"
                  type="text"
                  size="mini"
                >
                  <img src="@/assets/common/edit.png">
                </el-button>
                <!--删除-->
                <el-button
                  class="no-padding"
                  @click.stop="handleUserDelete(scope.row, scope.$index)"
                  type="text"
                  size="mini"
                >
                  <img src="@/assets/common/delete.png">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!--dialog-->
    <div>
      <!--用户-->
      <el-dialog
        :title="$t('message.userManage.dialog.user.title', {method: user.dialog.method})"
        :visible.sync="user.dialog.visible"
        @closed="handleUserDialogClosed"
        width="350px"
      >
        <el-form
          ref="userForm"
          :model="user.dialog.form"
          :rules="user.dialog.rules"
          label-width="110px"
        >
          <!--用户名-->
          <el-form-item
            :label="$t('message.userManage.dialog.user.form.label1')"
            prop="username"
          >
            <el-input v-model="user.dialog.form.username" />
          </el-form-item>
          <!--密码-->
          <el-form-item
            v-if="user.dialog.method === 'post'"
            :label="$t('message.userManage.dialog.user.form.label2')"
            prop="password"
          >
            <el-input
              type="password"
              v-model="user.dialog.form.password"
            />
          </el-form-item>
          <!--确认密码-->
          <el-form-item
            v-if="user.dialog.method === 'post'"
            :label="$t('message.userManage.dialog.user.form.label3')"
            prop="passwordConfirm"
          >
            <el-input
              type="password"
              v-model="user.dialog.form.passwordConfirm"
            />
          </el-form-item>
          <!--是否为管理员-->
          <el-form-item
            v-if="user.dialog.method === 'post'"
            :label="$t('message.userManage.dialog.user.form.label4')"
            prop="is_staff"
          >
            <el-switch
              v-model="user.dialog.form.is_staff"
              active-color="#4e6d9d"
              inactive-color="#C0C4CC"
            />
          </el-form-item>
          <!--修改-->
          <!--旧密码-->
          <el-form-item
            v-if="user.dialog.method === 'patch'"
            :label="$t('message.userManage.dialog.user.form.label5')"
            prop="old_password"
          >
            <el-input
              type="password"
              v-model="user.dialog.form.old_password"
            />
          </el-form-item>
          <!--新密码-->
          <el-form-item
            v-if="user.dialog.method === 'patch'"
            :label="$t('message.userManage.dialog.user.form.label6')"
            prop="new_password"
          >
            <el-input
              type="password"
              v-model="user.dialog.form.new_password"
            />
          </el-form-item>
          <!--再次输入新密码-->
          <el-form-item
            v-if="user.dialog.method === 'patch'"
            :label="$t('message.userManage.dialog.user.form.label7')"
            prop="new_password_confirm"
          >
            <el-input
              type="password"
              v-model="user.dialog.form.new_password_confirm"
            />
          </el-form-item>
          <el-form-item class="button-form-item">
            <el-button
              :loading="user.dialog.buttonLoading"
              @click="submitForm('userForm')"
              type="primary"
            >
              {{ $t('message.common.button.confirm') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserManage',
  data () {
    let validatePasswordConfirm = (rule, value, callback) => {
      setTimeout(() => {
        if (value !== this.user.dialog.form.password) {
          // 两次密码输入不一致
          callback(new Error(this.$t('message.userManage.validate.user.passwordConfirm.err1')))
        } else {
          callback()
        }
      }, 500)
    }
    let validateNewPasswordConfirm = (rule, value, callback) => {
      setTimeout(() => {
        if (value !== this.user.dialog.form.new_password) {
          // 两次密码输入不一致
          callback(new Error(this.$t('message.userManage.validate.user.new_password_confirm.err1')))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      loading: false,

      user: {
        table: {
          loading: false,
          data: []
        },

        dialog: {
          buttonLoading: false,
          visible: false,

          method: '',
          id: '',
          form: {
            username: '',
            password: '',
            passwordConfirm: '',
            is_staff: false,

            old_password: '',
            new_password: '',
            new_password_confirm: ''
          },
          rules: {
            username: [
              // 请输入用户名
              { required: true, message: this.$t('message.userManage.validate.user.username'), trigger: 'blur' }
            ],
            password: [
              // 请输入密码
              { required: true, message: this.$t('message.userManage.validate.user.password'), trigger: 'blur' }
            ],
            passwordConfirm: [
              // 请再次输入密码
              { required: true, message: this.$t('message.userManage.validate.user.passwordConfirm.err1'), trigger: 'blur' },
              { validator: validatePasswordConfirm, trigger: 'blur' }
            ],

            old_password: [
              // 请输入旧密码
              { required: true, message: this.$t('message.userManage.validate.user.old_password'), trigger: 'blur' }
            ],
            new_password: [
              // 请输入新密码
              { required: true, message: this.$t('message.userManage.validate.user.new_password'), trigger: 'blur' }
            ],
            new_password_confirm: [
              // 请再次输入新密码
              { required: true, message: this.$t('message.userManage.validate.user.new_password_confirm.err1'), trigger: 'blur' },
              { validator: validateNewPasswordConfirm, trigger: 'blur' }
            ]
          }
        }
      }
    }
  },
  mounted () {
    let self = this
    self.$nextTick(() => {
      self.getUserList()
    })
  },
  methods: {
    async getUserList () {
      let self = this
      try {
        self.user.table.loading = true
        let response = await self.$store.dispatch('axios', {
          method: 'get',
          url: '/api/abs/auth/users/'
        })
        self.user.table.data = response.data.results
      } finally {
        self.user.table.loading = true
      }
    },
    handleUserCreate () {
      let self = this
      self.user.dialog.method = 'post'
      self.user.dialog.visible = true
    },
    handleUserModify (row, index) {
      let self = this
      self.user.dialog.method = 'patch'
      self.user.dialog.id = row.id
      self.user.dialog.form.username = row.username
      self.user.dialog.form.is_staff = row.is_staff
      self.user.dialog.visible = true
    },
    handleUserDialogClosed () {
      let self = this
      self.user.dialog.method = ''

      self.user.dialog.form.username = ''
      self.user.dialog.form.password = ''
      self.user.dialog.form.passwordConfirm = ''
      self.user.dialog.form.is_staff = false

      self.user.dialog.form.old_password = ''
      self.user.dialog.form.new_password = ''
      self.user.dialog.form.new_password_confirm = ''
    },
    async handleUserDelete (row, index) {
      let self = this
      try {
        await self.$confirm(`此操作将永久删除${row.username}用户，是否继续？`, self.$t('message.common.label.prompt'), {
          confirmButtonText: self.$t('message.common.button.confirm'),
          cancelButtonText: self.$t('message.common.button.cancel'),
          type: 'warning'
        })
      } catch (e) {
        return
      }
      await self.$store.dispatch(`axios`, {
        method: 'delete',
        url: `/api/abs/auth/users/${row.id}/`
      })
      self.$message({
        message: self.$t('message.common.info.deleteSuccess'),
        type: 'success'
      })
      self.user.table.data.splice(index, 1)
    },
    async submitForm (formName) {
      let self = this
      try {
        await self.$refs[formName].validate()
      } catch (e) {
        return
      }
      if (formName === 'userForm') {
        if (self.user.dialog.method === 'post') {
          let response = await self.$store.dispatch('axios', {
            method: 'post',
            url: '/api/abs/auth/users/',
            data: {
              username: self.user.dialog.form.username,
              password: self.user.dialog.form.password,
              is_staff: self.user.dialog.form.is_staff
            }
          })
          self.user.table.data.push(response.data)
          self.$message.success('添加用户成功')
          self.user.dialog.visible = false
        } else if (self.user.dialog.method === 'patch') {
          await self.$store.dispatch('axios', {
            method: 'post',
            url: `/api/abs/auth/users/${self.user.dialog.id}/password/`,
            data: {
              old_password: self.user.dialog.form.old_password,
              new_password: self.user.dialog.form.new_password
            }
          })
          self.$message.success('修改用户成功')
          self.user.dialog.visible = false
        }
      }
    }
  }
}
</script>

<style scoped>
  .config-row{
    text-align: left;
  }
</style>
